/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package uk.ac.susx.inf.ianw.shareManagement.services.impl;

import uk.ac.susx.inf.ianw.shareManagement.entities.ShareTransaction;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;

@Stateless(name = "shareTransactionService")
public class ShareTransactionService {

    @PersistenceUnit
    private EntityManagerFactory emf;

    public void create(ShareTransaction shareTransaction) throws Exception {
        EntityManager em = emf.createEntityManager();
        em.persist(shareTransaction);
        em.flush();
    }

    public void update(ShareTransaction shareTransaction) throws Exception {
        EntityManager em = emf.createEntityManager();
        em.merge(shareTransaction);
        em.flush();
    }

    public void delete(Long id) throws Exception {
        EntityManager em = emf.createEntityManager();
        ShareTransaction transaction = em.find(ShareTransaction.class, id);
        em.remove(transaction);
        em.flush();
    }

    public List<ShareTransaction> readList() throws Exception {
        EntityManager em = emf.createEntityManager();
        return em.createNamedQuery("ShareTransaction.readList").getResultList();
    }

    public Integer getShareCount(String company) throws Exception {
        Integer result = 0;
        EntityManager em = emf.createEntityManager();
        List<ShareTransaction> list = em.createNamedQuery("ShareTransaction.readListByCompany").setParameter("company", company).getResultList();
        if(list == null){
            result = 0;
        } else{
            for(ShareTransaction transaction : list){
                result = result + transaction.getAmount();
            }
        }
        return result;
    }
}
